package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.wxaapp.api.WxaAccessTokenApi;
import com.platform.annotation.IgnoreAuth;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.platform.util.wechat.WechatUtil.setWxaConfig;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "首页接口文档")
@RestController
@RequestMapping("/api/index")
public class ApiIndexController extends ApiBaseAction {
    @Autowired
    private ApiAdPositionService adPositionService;
    @Autowired
    private ApiAdService adService;
    @Autowired
    private ApiChannelService channelService;
    @Autowired
    private ApiGoodsService goodsService;
    @Autowired
    private ApiBrandService brandService;
    @Autowired
    private ApiTopicService topicService;
    @Autowired
    private ApiCategoryService categoryService;
    @Autowired
    private ApiCartService cartService;
    @Autowired
    private ApiAnnouncementService announcementService;
    @Autowired
    private ApiVideoService videoService;
    @Autowired
    private ApiSysMacroService sysMacroService;
    @Resource
    private RabbitTemplate amqpTemplate;


    @IgnoreAuth
    @RequestMapping(value = "/rmq.do")
    public Object sendMsg() {
        Map<String, Object> item = new HashMap<>();
        item.put("id", 5);
        amqpTemplate.convertAndSend("test_rmq_exchange", "order_submit_queue_patt", item);
        return R.ok();
    }

    @IgnoreAuth
    @RequestMapping(value = "sheng", method = {RequestMethod.GET, RequestMethod.POST})
    public Object sheng() {
        //创建小程序码
        try {
            setWxaConfig();
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + WxaAccessTokenApi.getAccessTokenStr());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpURLConnection.setRequestMethod("POST");
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", 1);
            paramJson.put("page", "pages/yuanDanEvent/yuanDanEvent");
            paramJson.put("width", 860);
            paramJson.put("auto_color", true);

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

            OutputStream os = new FileOutputStream(new File("C:\\Users\\czjcz\\Desktop\\yuanDanEvent.png"));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     * 获取字典的值
     *
     * @param key 钥匙
     * @return 值
     */
    @IgnoreAuth
    @RequestMapping(value = "getWordbookValue", method = {RequestMethod.GET, RequestMethod.POST})
    public Object getWordbookValue(@RequestParam String key) {
        String value = sysMacroService.queryValueByName(key);
        return toResponsSuccess(value);
    }

    /**
     * 获取广告列表
     */
    @IgnoreAuth
    @RequestMapping(value = "spreadList", method = {RequestMethod.GET, RequestMethod.POST})
    public Object adList(@RequestParam Integer id) {
        AdPositionVo adPositionVo = adPositionService.queryObject(id);
        if (adPositionVo == null) {
            return toResponsFail("不存在该广告模块");
        }
        Integer adPositionId = adPositionVo.getId();

        Map<String, Object> params = new HashMap<>();
        params.put("ad_position_id", adPositionId);
        params.put("sidx", "sort_order");
        params.put("order", "desc");

        List<AdVo> adList = adService.queryList(params);

        adPositionVo.setAdList(adList);

        return toResponsSuccess(adPositionVo);
    }

    /**
     * app首页
     */
    @ApiOperation(value = "首页")
    @IgnoreAuth
    @RequestMapping(value = "index", method = {RequestMethod.GET, RequestMethod.POST})
    public Object index() {
        Map<String, Object> resultObj = new HashMap<>();
        //
        Map<String, Object> param = new HashMap<>();
        param.put("ad_position_id", 1);
        List<AdVo> banner = adService.queryList(param);
        resultObj.put("banner", banner);
        //
        param = new HashMap<>();
        param.put("sidx", "sort_order ");
        param.put("order", "asc ");
        List<ChannelVo> channel = channelService.queryList(param);
        resultObj.put("channel", channel);
        //
        param = new HashMap<>();
        param.put("is_new", 1);
        param.put("offset", 0);
        param.put("limit", 4);
        param.put("is_delete", 0);
        param.put("fields", "id, name, list_pic_url, retail_price");
//        List<GoodsVo> newGoods = goodsService.queryList(param);
//        resultObj.put("newGoodsList", newGoods);
        //
        param = new HashMap();
        param.put("is_hot", "1");
        param.put("offset", 0);
        param.put("limit", 3);
        param.put("is_delete", 0);
        List<GoodsVo> hotGoods = goodsService.queryHotGoodsList(param);
        resultObj.put("hotGoodsList", hotGoods);
        // 当前购物车中
        List<CartVo> cartList = new ArrayList();
        if (null != getUserId()) {
            //查询列表数据
            Map cartParam = new HashMap();
            cartParam.put("user_id", getUserId());
            cartList = cartService.queryList(cartParam);
        }
        if (null != cartList && cartList.size() > 0 && null != hotGoods && hotGoods.size() > 0) {
            for (GoodsVo goodsVo : hotGoods) {
                for (CartVo cartVo : cartList) {
                    if (goodsVo.getId().equals(cartVo.getGoods_id())) {
                        goodsVo.setCart_num(cartVo.getNumber());
                    }
                }
            }
        }
        //公告
        param = new HashMap<>();
        param.put("enabled", 1);
        List<AnnouncementVo> announcementList = announcementService.queryList(param);
        resultObj.put("announcementList", announcementList);
        //视频
        param = new HashMap<>();
        param.put("enabled", 1);
        param.put("offset", 0);
        param.put("limit", 1);
        List<VideoVo> videoList = videoService.queryList(param);
        if (videoList.size() > 0) {
            resultObj.put("indexVideo", videoList.get(0));
        } else {
            resultObj.put("indexVideo", null);
        }
//        param = new HashMap();
//        param.put("offset", 0);
//        param.put("limit", 3);
//        List<TopicVo> topicList = topicService.queryList(param);
//        resultObj.put("topicList", topicList);
        // 团购
//        param = new HashMap();
//        param.put("offset", 0);
//        param.put("limit", 3);
//        List<GoodsGroupVo> goodsGroupVos = goodsGroupService.queryList(param);
//        resultObj.put("topicList", goodsGroupVos);
        // 砍价
//        param = new HashMap();
//        param.put("offset", 0);
//        param.put("limit", 3);
//        List<GoodsGroupVo> goodsGroupVos = goodsGroupService.queryList(param);
//        resultObj.put("topicList", goodsGroupVos);
        //
//        param = new HashMap();
//        param.put("parent_id", 0);
//        param.put("notName", "推荐");//<>
//        List<CategoryVo> categoryList = categoryService.queryList(param);
//        List<Map> newCategoryList = new ArrayList<>();
//
//        for (CategoryVo categoryItem : categoryList) {
//            param.remove("fields");
//            param.put("parent_id", categoryItem.getId());
//            List<CategoryVo> categoryEntityList = categoryService.queryList(param);
//            List<Integer> childCategoryIds = new ArrayList<>();
//            for (CategoryVo categoryEntity : categoryEntityList) {
//                childCategoryIds.add(categoryEntity.getId());
//            }
//            //
//            param = new HashMap();
//            param.put("categoryIds", childCategoryIds);
//            param.put("fields", "id as id, name as name, list_pic_url as list_pic_url, retail_price as retail_price");
//            List<GoodsVo> categoryGoods = goodsService.queryList(param);
//            Map newCategory = new HashMap();
//            newCategory.put("id", categoryItem.getId());
//            newCategory.put("name", categoryItem.getName());
//            newCategory.put("goodsList", categoryGoods);
//            newCategoryList.add(newCategory);
//        }
//        resultObj.put("categoryList", newCategoryList);
        return toResponsSuccess(resultObj);
    }
}